package org.ala.tiktools.generator.mybatis.dbinfo;

import org.ala.tiktools.generator.mybatis.config.info.DBMS;
import org.ala.tiktools.generator.mybatis.config.info.Part;

import java.io.UnsupportedEncodingException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 数据库连接类
 *
 * @author ala
 * @date 2024-12-31 10:32
 */
public class DBConnector {


    /**
     *  dbms信息
     */
    protected DBMS dbms;
    /**
     *  链接
     */
    protected Connection conn;
    /**
     *  拿数据
     */
    protected DBInfoGatter gatter = new DBInfoGatter();

    public DBConnector(DBMS dbms) {
        this.dbms = dbms;
        this.conn = getConnection();
    }

    public static DBConnector build(DBMS dbms) {
        return new DBConnector(dbms);
    }

    /**
     *  根据dbms拿一个链接
     */
    public Connection getConnection() {
        try {
            //  检测是否有驱动程序
            Class.forName(dbms.getJdbc());
            return DriverManager.getConnection(dbms.getUrl(), dbms.getUsername(), dbms.getPassword());
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     *  取表信息
     */
    public TableInfo tableInfo(Part p, String db, String name, String charset) {
        try {
            //  表信息
            TableInfo tinfo = gatter.getTable(conn, db, name);

            //  取字段信息
            tinfo.setColumns(gatter.getColumns(conn, db, name));
            //  找主键
            tinfo.getColumns().forEach(f -> {
                if (f.onlyAutoIncrementPrimaryKey) {
                    tinfo.setOnlyAutoIncrementPrimaryKey(f);
                }
            });

            tinfo.setShardTable(p.isShardTable());
            tinfo.setCreateSql(gatter.getCreateSql(conn, db, name));
            tinfo.setCreateIndexSql(gatter.getCreateIndexSql(conn, db, name));
            tinfo.setAllTablesSql(gatter.getAllTablesSql(db, name));
            return tinfo;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
